package com.feihong.yw189.activity.kuandai;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.buka.BukaActivity;
import com.feihong.yw189.activity.dingdan.DingDanDetailsActivity;
import com.feihong.yw189.activity.kaika.KaiKaActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ImageTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.model.Kaika.UpLoadPicModel;

import org.xutils.common.Callback;

import java.io.File;


public class HengXiangSign extends Activity {
    private PaintView mView;
    private FrameLayout fm_sign;
    private ImageView iv_back;
    private String filename = "";
    private String money = "";
    // private MyUsualyDialog dialog;

    private String path = "";
    private ImageView btn_ok_sign;
    private ImageView btn_cx_sign;
    private String position;
    private Intent mIntent;
    public static final String BEIMIAN_URL_REP = "";
    /**
     * 图片路径
     */
    private String signFilePath;
    public static final String SIGN_IMG__URL_REP = "SIGN_IMG__URL_REP";
    public static final String SIGN_IMG__URL = "SIGN_IMG__URL";
    public static final String SIGN_IMG__RESULT = "SIGN_IMG";
    MyUsualyDialog mydialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heng_xiang_sign);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // 透明状态栏
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        position = getIntent().getStringExtra("position");
        mydialog = new MyUsualyDialog(HengXiangSign.this, R.layout.wait_item);
        mydialog.setCanceledOnTouchOutside(true);
        mydialog.setCancelable(false);

        initView();
    }

    //设置android app 的字体大小不受系统字体大小改变的影响
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    private void initView() {
        fm_sign = (FrameLayout) findViewById(R.id.fm_sign);
        btn_ok_sign = (ImageView) findViewById(R.id.btn_ok_sign);
        btn_cx_sign = (ImageView) findViewById(R.id.btn_cx_sign);
        iv_back = (ImageView) findViewById(R.id.iv_back);
    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        initData();
        super.onResume();
    }

    //点击返回键，返回上一个页面，而不是退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initData() {
        // 签名
        mView = new PaintView(this);
        fm_sign.addView(mView);
        mView.requestFocus();
        btn_cx_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 重新签名
                mView.clear();
            }
        });
        btn_ok_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(flag)) {
                    //dialog.show();
                    btn_ok_sign.setEnabled(false);
                    // 保存签名图片
                    savePhotoToSDCard();
                } else {
                    // 带回需要的数据
                    ToastUtils.showLong("请确认签名");
                }
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 保存签名图片
     */
    public void savePhotoToSDCard() {
        // 获取签名图片
        if (!mydialog.isShowing()) {
            mydialog.show();
            mydialog.setWarningTxt(R.id.progress_layout_warning_tv,"签名上传中");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = mView.getCachebBitmap();
                    // 如果保存的图片为黑色的话,先设置背景为白色
                    Bitmap outB = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                    Canvas canvas = new Canvas(outB);
                    canvas.drawColor(Color.WHITE);
                    canvas.drawBitmap(bitmap, 0, 0, null);

                    path = getExternalCacheDir() + "/yw189_signphotos";
                    ImageTools.savePhotoToSDCard(outB, path, "sign");
                    final File photoFile = new File(path, "sign" + ".png");
                    imageUpload(photoFile);
                } catch (Exception ex) {
                    btn_ok_sign.setEnabled(true);
                }
            }
        }).start();
    }

    /**
     * 上传图片
     */
    private void imageUpload(File file) {
        App.getApp().getHttpTools().uploadFile(file, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    UpLoadPicModel up = JSON.parseObject(result, UpLoadPicModel.class);
                    if (up != null) {
                        if (up.getStatus() == 1) {
                            String handSignUrl = up.getData().getUrl();
                            String handSignRep = up.getData().getUrl_rep();
                            if (!position.isEmpty()) {
                                if (position.equals("510")) {
                                    mIntent = new Intent(HengXiangSign.this, KaiKaActivity.class);
                                } else if (position.equals("511")) {
                                    mIntent = new Intent(HengXiangSign.this, KaiKaActivity.class);
                                } else if (position.equals("1127")) {
                                    mIntent = new Intent(HengXiangSign.this, DingDanDetailsActivity.class);
                                }else if(position.equals("512")){
                                    mIntent = new Intent(HengXiangSign.this, BukaActivity.class);
                                }
                            }
                            if (mIntent == null) {
                                return;
                            }
                            Bundle bundle = new Bundle();
                            bundle.putString("handSignUrl", handSignUrl);
                            bundle.putString(SIGN_IMG__URL_REP, handSignRep);
                            bundle.putString(SIGN_IMG__URL, handSignUrl);
                            bundle.putString(SIGN_IMG__RESULT, result);
                            mIntent.putExtras(bundle);

                            setResult(RESULT_OK, mIntent); // 成功返回100

                            finish();
                        } else {
                            ToastUtils.showLong("" + up.getInfo());
                        }
                    } else {
                        ToastUtils.showShort("数据出错,请重试");
                    }
                } catch (Exception ex) {
                    ToastUtils.showShort("数据出错,请重试");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showShort("请检查网络");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
                mydialog.dismiss();
                btn_ok_sign.setEnabled(true);

            }
        });

    }

    // 标记是否签名
    private String flag = "0";

    /**
     * 签名
     */
    class PaintView extends View {
        private Paint paint;
        private Canvas cacheCanvas;
        private Bitmap cachebBitmap;
        private Path path;

        /**
         * 返回签名bitmap
         */
        public Bitmap getCachebBitmap() {
            return cachebBitmap;
        }

        public PaintView(Context context) {
            super(context);
            init();
        }

        private void init() {
            paint = new Paint();
            paint.setAntiAlias(true);
            paint.setFakeBoldText(true);
            paint.setStrokeWidth(10.0f);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.BLACK);
            path = new Path();
            cachebBitmap = Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
            cacheCanvas = new Canvas(cachebBitmap);
            cacheCanvas.drawColor(Color.TRANSPARENT);
        }

        public void clear() {
            flag = "0";
            if (cacheCanvas != null) {
                paint.setColor(Color.parseColor("#FBFBFB"));
                cacheCanvas.drawPaint(paint);
                paint.setColor(Color.BLACK);
                cacheCanvas.drawColor(Color.TRANSPARENT);
                invalidate();
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawBitmap(cachebBitmap, 0, 0, null);
            canvas.drawPath(path, paint);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {

            try {
                int curW = cachebBitmap != null ? cachebBitmap.getWidth() : 0;
                int curH = cachebBitmap != null ? cachebBitmap.getHeight() : 0;
                if (curW >= w && curH >= h) {
                    return;
                }
                if (curW < w)
                    curW = w;
                if (curH < h)
                    curH = h;

                Bitmap newBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
                Canvas newCanvas = new Canvas();
                newCanvas.setBitmap(newBitmap);
                if (cachebBitmap != null) {
                    newCanvas.drawBitmap(cachebBitmap, 0, 0, null);
                }
                cachebBitmap = newBitmap;
                cacheCanvas = newCanvas;
            } catch (Exception ex) {
            }

        }

        private float cur_x, cur_y;

        @Override
        public boolean onTouchEvent(MotionEvent event) {

            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    cur_x = x;
                    cur_y = y;
                    path.moveTo(cur_x, cur_y);
                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    flag = "1";
                    path.quadTo(cur_x, cur_y, x, y);
                    cur_x = x;
                    cur_y = y;
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    cacheCanvas.drawPath(path, paint);
                    path.reset();
                    break;
                }
                default:
                    break;
            }
            invalidate();
            return true;
        }
    }

    public class ImageInfo {
        String code;
        String msg;
        String filename;
        String money;
    }
}
